package com.ego.item.config;

import com.ego.item.properties.AuthProperties;
import com.ego.item.properties.JwtProperties;
import com.ego.utils.JwtUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Component
@EnableConfigurationProperties({AuthProperties.class, JwtProperties.class})
public class AuthFilter implements GlobalFilter, Ordered {


    @Resource
    private AuthProperties authProperties;
    @Resource
    private JwtProperties jwtProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断是否需要鉴权
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getPath().toString();

        boolean isAllow = authProperties.getAllowUrlList().stream().anyMatch(allowPath -> path.startsWith(allowPath));
        //1.不需要->直接放行
        if (isAllow) {
            return chain.filter(exchange);
        }
        else
        {

            try {
                //2.需要 ->通过公钥解密鉴权
                String token = request.getCookies().getFirst(jwtProperties.getCookieName()).getValue();
                JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            } catch (Exception e) {
                e.printStackTrace();
                //2.1.鉴权失败->返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }
        //2.2.鉴权成功->放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
